package controller

import (
	"appService/src/application"
	"appService/src/application/admin/admin/adminModels"
	"appService/src/application/app/appModels"
	"appService/src/application/app/authGroup"
	"appService/src/authValid"
	"appService/src/orm"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"xorm.io/builder"
)

//Api 数据接口
type Api struct {
	application.BaseController
}

//getModel 获取控制器对应的 模型
func  (*Api)getModel() appModels.IModel{
	return new(adminModels.Api)
}
//List 获取需要 指定权限才访问的数据接口列表
func (this *Api) List(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	p:= struct {
		AuthGroupId string `json:"auth_group_id"`
	}{}
	req.ParamsAnalyse(&p)
	list := make([]adminModels.Api, 0)
	err := orm.Db.Where(builder.Eq{"is_show": 1, "enable": 1 }.And(builder.In("visit", []int{3, 4})).And(builder.In("auth_group_id",[]string{p.AuthGroupId,authGroup.SHARE_ID}))).Desc("sort").Find(&list)
	if err != nil {
		g.Log().Errorf("查询【数据接口】列表，错误：%v", err)
		req.JsonError("获取列表失败")
	} else {
		req.JsonSuccessData(list)
	}
}

//Delete 删除
func (this *Api) Delete(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	p := struct {
		Ids []string `json:"ids"`
	}{}
	req.ParamsAnalyse(&p)
	if len(p.Ids) == 0 {
		req.JsonError("请选择要删除的数据")
	}
	list := make([]adminModels.Api, 0)
	err := orm.Db.In("id", p.Ids).Find(&list)
	if err != nil {
		g.Log().Errorf("查询要删除的数据接口，错误：%v", err)
		req.JsonError("删除失败")
	}
	_, err = orm.Db.In("id", p.Ids).Delete(new(adminModels.Api))
	if err == nil {
		for _, a := range list {
			authValid.ApiRemove(a.AuthCode)
		}
		req.JsonSuccess("删除成功")
	} else {
		g.Log().Errorf("删除数据接口，错误：%v", err)
		req.JsonError("删除失败")
	}
}

//Edit 修改
func (this *Api) Edit(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.EditHandle(func() {
		res := req.Model.(*adminModels.Api)
		api := new(adminModels.Api)
		has, err := orm.Db.Where(builder.Eq{"id": res.Id}).Get(api)
		if err == nil && has {
			authValid.ApiSet(api)
		}
	})
}

func (this *Api) ListPaginate(r *ghttp.Request){
	this.NewRequest(r,this.getModel()).ListPaginate()
}